var ListNode = function (value) {
  this.val = value;
  this.next = null;
};
var MyLinkedList = function () {
  this.size = 0;
  this.head = null;
};

/**
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function (index) {
  if (index < 0 || (index+1) > this.size) return -1;
  let node = this.head;
  while (index--) {
    node = node.next;
  }
  return node ? node.val : -1;
};

/**
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtHead = function (val) {
  let s = new ListNode(val);
  s.next = this.head;
  this.head = s;
  this.size++;
};

/**
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function (val) {
  let s = new ListNode(val);
  if (this.size === 0) {
    this.head = s;
  } else {
    let p = this.head;
    while (p.next != null) {
      p = p.next;
    }
    p.next = s;
  }
  this.size++;
};

/**
 * @param {number} index
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function (index, val) {
  if (index > this.size || index < 0) return;
  if (index === 0) {
    this.addAtHead(val);
  } else if (index === this.size) {
    this.addAtTail(val);
  } else {
    let s = new ListNode(val);
    let pre = new ListNode(0);
    pre.next = this.head;
    while (index--) {
      pre = pre.next;
    }
    s.next = pre.next;
    pre.next = s;
    this.size++;
  }
};

/**
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function (index) {
    console.log(this.size);
  if (index < 0 || (index+1) > this.size) return;
  if (index === 0) {
    this.head = this.head.next;
  } else {
    let pre = new ListNode(0);
    pre.next = this.head;
    while (index--) {
      pre = pre.next;
    }
    pre.next = pre.next.next;
  }

  this.size--;
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * var obj = new MyLinkedList()
 * var param_1 = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index,val)
 * obj.deleteAtIndex(index)
 */

let myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(0);
myLinkedList.addAtIndex(1, 1); // 链表变为 1->2->3
console.log(myLinkedList.get(2)); // 返回 2
myLinkedList.addAtHead(4);
console.log(myLinkedList.get(2)); // 返回 2
myLinkedList.addAtHead(4);
console.log(myLinkedList.get(2)); // 返回 2
// console.log(myLinkedList.get(3)); // 返回 2
// myLinkedList.addAtIndex(1, 6); // 链表变为 1->2->3

// myLinkedList.addAtTail(1);
// myLinkedList.addAtHead(0);


// myLinkedList.deleteAtIndex(1); // 现在，链表变为 2->3

// console.log(myLinkedList.get(1));
console.log(myLinkedList, "list");
